<?php

namespace App\Http\Model;

use App\Lib\Search;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Musics extends Base
{
    protected $table = 'music';
    protected $fillable = ['music_id', 'music_name', 'music_url', 'user_id', 'created_time', 'md5'];
    private $redisCacheMyMusic = 'CACHE:MY_MUSIC:';                                             // HASH
    private $redisCacheMyMusicSort = 'CACHE:MY_MUSIC:SORT:';
    protected $redis_room_music_permission = 'CACHE:ROOM:MUSIC:PERMISSION:';


    // public function getMusicUrlAttribute($musicUrl) {
    //   return env('APP_PIC_DOMAIN').DIRECTORY_SEPARATOR.$musicUrl;
    // }

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function createData($data = [])
    {
        return DB::table($this->table)->insertGetId([
            'music_name' => $data['music_name'],
            'music_url' => $data['music_url'],
            'author' => $data['author'],
            'user_id' => $data['user_id'],
            'md5' => $data['md5'],
            'status' => $data['status']
        ]);
    }

    /**获取音乐列表
     * @param int $page
     * @param int $pageSize
     * @return mixed
     */
    public function getList(int $page, int $pageSize)
    {
        $musics = DB::table($this->table)
            ->offset($page * $pageSize)
            ->limit($pageSize)
            ->where($this->table . '.status', 1)
            ->orderByRaw("music_id desc,down_total desc")
            ->get();
        $musics = self::objToArray($musics);
        return $musics;
    }

    public function isExists($musicName)
    {
        return self::where('music_name', $musicName)->count();
    }

    /**
     * Redis HASH, 我的音乐
     *
     * @param integer $userId
     * @param integer $musicId
     * @param array $music
     * @return void
     */
    public function setMyMusic(int $userId, int $musicId, array $music)
    {
        $music = json_encode($music);
        $redisKey = $this->redisCacheMyMusic . $userId;
        $redisSortKey = $this->redisCacheMyMusicSort . $userId;
        Redis::MULTI();
        Redis::HSET($redisKey, $musicId, $music);
        Redis::ZADD($redisSortKey, time(), $musicId);
        Redis::EXEC();
    }

    /**根据音乐ID获取音乐
     * @param int $musicId
     * @return array|mixed
     */
    public function getMusicById(int $musicId)
    {
        $music = DB::table($this->table)->where('music_id', $musicId)->first();
        if (!$music) {
            return [];
        }
        return $this->objToArray($music);
    }

    /**
     * 获取我的音乐
     *
     * @param integer $userId
     * @return void
     */
    public function getMyMusic(int $userId)
    {
        $redisKey = $this->redisCacheMyMusic . $userId;
        $redisSortKey = $this->redisCacheMyMusicSort . $userId;
        $musics = Redis::HGETALL($redisKey);
        $musicsSort = Redis::ZREVRANGEBYSCORE($redisSortKey, '+inf', '-inf', ['withscores' => true]);
        $appPicDomain = env('APP_PIC_DOMAIN');

        $myMusics = [];
        foreach ($musics as $music) {
            $music = json_decode($music, true);
            $music['music_url'] = $appPicDomain . DIRECTORY_SEPARATOR . $music['music_url'];
            $music['s'] = $musicsSort[$music['music_id']] ?? 0;
            array_push($myMusics, $music);
        }

        // 按下载时间排序
        $myMusics = arraySort($myMusics, 's');
        unset($music);
        return $myMusics;
    }

    /**删除我的音乐
     * @param int $musicId
     * @return int
     */
    public function deleteMusic(int $musicId)
    {
        return DB::table($this->table)->where(['music_id'=> $musicId])->delete();
    }

    /**音乐审核
     * @param int $musicId
     * @param int $status
     * @param int $checkId
     * @param string $remark
     * @return int
     */
    public function setAudit(int $musicId, int $status ,int $checkId ,string $remark = '')
    {
        return DB::table($this->table)
            ->where('music_id', $musicId)
            ->update(['status' => $status ,'check_id'=>$checkId ,
                'remark'=>$remark ,'update_time'=>time()]);
    }

    /**
     * 下载量
     *
     * @param integer $musicId
     * @return void
     */
    public function incDownTotal(int $musicId)
    {
        DB::table($this->table)->where('music_id', $musicId)->increment('down_total', 1);
    }

    /**设置播放音乐权限
     * @param $room_id
     * @param $user_id
     */
    public function setMusicPermission($room_id ,$user_id){
        Redis::SADD($this->redis_room_music_permission.$room_id ,$user_id);
    }

    /**删除播放音乐权限
     * @param $room_id
     * @param int $user_id
     */
    public function delMusicPermission($room_id ,$user_id = 0){
        if(!empty($user_id)){
            Redis::SREM($this->redis_room_music_permission.$room_id ,$user_id);
        }else{
            Redis::del($this->redis_room_music_permission.$room_id);
        }

    }

    /**获取播放音乐的权限
     * @param $room_id
     * @param $user_id
     * @return mixed
     */
    public function getMusicPermission($room_id ,$user_id){
        if(!empty($user_id)){
            return Redis::SISMEMBER($this->redis_room_music_permission.$room_id ,$user_id);
        }
        return Redis::SMEMBERS($this->redis_room_music_permission.$room_id);
    }
}
